package com.yesallchina.wxapp.officialaccount.api;

import com.fasterxml.jackson.databind.JsonNode;
import com.yesallchina.wxapp.officialaccount.api.beans.ParamName;
import com.yesallchina.wxapp.officialaccount.api.beans.QrcodeCreatedResultDTO;
import com.yesallchina.wxapp.officialaccount.api.beans.param.QrcodeParam;
import com.yesallchina.wxapp.officialaccount.service.WxOfficialAccountInitializer;
import com.yesallchina.wxapp.officialaccount.utils.JacksonUtils;
import com.yesallchina.wxapp.officialaccount.utils.WxHttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 账号管理
 */
public class AccountManageApi {

    private final static Logger log = LoggerFactory.getLogger(AccountManageApi.class);

    private WxOfficialAccountInitializer wxInit;

    private BasicSupportApi basicSupportApi;

    public AccountManageApi(BasicSupportApi basicSupportApi) {
        this.basicSupportApi = basicSupportApi;
        this.wxInit = basicSupportApi.getWxInit();
    }

    /**
     * 生成带参数的二维码
     *
     * @return
     */
    public QrcodeCreatedResultDTO qrcodeCreate(QrcodeParam param) {
        return qrcodeCreate(0, param);
    }

    private QrcodeCreatedResultDTO qrcodeCreate(int retry, QrcodeParam param) {
        if (retry > 2) {
            log.error("[创建二维码]：失败，参数 \r\n {}", param.toCreateQrcode());
            return null;
        }
        try {
            String url = wxInit.getApiProp().getQrcodeCreate();
            url += "?" + ParamName.ACCESS_TOKEN + "=" + basicSupportApi.getAccessToken();
            String response = WxHttpUtils.postJSON(url, param.toCreateQrcode(), wxInit.getCommonProp());
            if (log.isDebugEnabled()) {
                log.debug("[创建二维码] : {}", response);
            }
            if (BasicSupportApi.isError(response)) {
                if (basicSupportApi.isInvalidAccessToken(response)) {
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
                    return qrcodeCreate(++retry, param);
                }
            }
            JsonNode qrcodeNode = JacksonUtils.parse(response, JsonNode.class);
            QrcodeCreatedResultDTO result = new QrcodeCreatedResultDTO();
            result.setTicket(qrcodeNode.get(ParamName.QRCODE_TICKET).asText());
            result.setUrl(qrcodeNode.get(ParamName.URL).asText());
            return result;
        } catch (Exception e) {
            try {
                Thread.sleep(1000);
            } catch (Exception ex) {
            }
            return qrcodeCreate(++retry, param);
        }
    }

    /**
     * 短连接生成
     *
     * @return
     */
    public String shorturlCreate(String longurl) {
        return shorturlCreate(longurl, 0);
    }


    private String shorturlCreate(String longurl, int retry) {
        if (retry > 2) {
            log.error("[创建短连接]：失败，参数 \r\n", longurl);
            return null;
        }
        try {
            String url = wxInit.getApiProp().getShorturlCreate()
                    + "?" + ParamName.ACCESS_TOKEN + "=" + basicSupportApi.getAccessToken();
            Map<String, String> params = new HashMap<>();
            params.put(ParamName.ACTION, "long2short");
            params.put(ParamName.LONG_URL, longurl);
            String response = WxHttpUtils.postJSON(url, params, wxInit.getCommonProp());
            if (basicSupportApi.isError(response)) {
                if (basicSupportApi.isInvalidAccessToken(response)) {
                    Thread.sleep(1000);
                    return shorturlCreate(longurl, ++retry);
                }
            }
            JsonNode urlNode = JacksonUtils.parse(response, JsonNode.class);
            return urlNode.get(ParamName.SHORT_URL).asText();
        } catch (Exception e) {
            try {
                Thread.sleep(1000);
            } catch (Exception ex) {
            }
            return shorturlCreate(longurl, ++retry);
        }
    }

}
